package top.yeyusmile.common;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.yeyusmile.mirai.AddReq;
import top.yeyusmile.mirai.PushMessage;

import top.yeyusmile.service.BlackWordService;
import top.yeyusmile.utils.HttpUtil;
import top.yeyusmile.utils.MiraiApiUtil;

import java.io.IOException;
import java.util.List;

/**
 * @author 夜雨
 * @Web www.yeyusmile.top
 * @date 2022/3/15 23:46
 */
@Component
@Slf4j
public class MyTemplate {

    @Autowired
    private RobotConfig config;


    @Autowired
    private BlackWordService blackWordService;

    /**
     * 发群信息
     *
     * @param params
     * @return
     */
    public String sendMsg2Group(List<Object> params, Integer quote, Long group) {
        PushMessage pushMessage = new PushMessage(config.getSessionKey(), group, params);
        pushMessage.setQuote(quote);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(pushMessage));

        if (blackWordService.isBlackWord(new Gson().toJson(pushMessage))) {
            log.warn("detected black word");
            return "detected black word";
        }

        if (blackWordService.isBan(group)) return "检测到禁言，已取消";

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("请求{}：", new Gson().toJson(pushMessage));

        MiraiApiUtil.httpPost(config.getRobotUrl() + "/sendGroupMessage", config.getSessionKey(),
                body, group + "", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        log.error(e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String respStr = response.body().string();
                        log.info("respStr:{}", respStr);
                        //{"code":20,"msg":"Bot被禁言"}
                        if (respStr.contains("Bot被禁言")) {
                            Long gid = Long.parseLong(call.request().header("gid"));
                            blackWordService.addBanGroupID(gid);
                        }

                        response.close();
                    }
                });
        return "resp";
    }


    /**
     * 好友申请操作
     *
     * @param addFriendReq
     * @return
     */
    public String opNewFried(AddReq addFriendReq) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(addFriendReq));
        log.info("请求{}：", new Gson().toJson(addFriendReq));
        MiraiApiUtil.httpPost(config.getRobotUrl() + "/resp/newFriendRequestEvent",
                config.getSessionKey(), body, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        log.error(e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        log.info(response.body().string());
                        response.close();
                    }
                });
        return "resp";
    }

    /**
     * 被邀请进群处理
     *
     * @param addGroup
     * @return
     */
    public String opBeinviteGrop(AddReq addGroup) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(addGroup));
        log.info("请求{}：", new Gson().toJson(addGroup));
        MiraiApiUtil.httpPost(
                config.getRobotUrl() + "/resp/botInvitedJoinGroupRequestEvent",
                config.getSessionKey(), body, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        log.error(e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        log.info(response.body().string());
                        response.close();
                    }
                });
        return "resp";
    }


    /**
     * 禁言解禁
     *
     * @return type 1禁言  0解禁  time=null
     */
    public String mute(Integer time, Long memberId, Long group, int type) {
        PushMessage pushMessage = new PushMessage(config.getSessionKey(), group, null);
        pushMessage.setTime(time);
        pushMessage.setMemberId(memberId);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(pushMessage));
        log.info("请求禁言/解禁{}：", new Gson().toJson(pushMessage));
        String url = "";
        if (type == 1) {
            url = config.getRobotUrl() + "/mute";
        } else {
            url = config.getRobotUrl() + "/unmute";
        }
        MiraiApiUtil.httpPost(url, config.getSessionKey(),
                body, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        log.error(e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println(response.body().string());
                        response.close();
                    }
                });
        return "resp";
    }

    /**
     * 发信息给好友
     *
     * @param params
     * @param quote
     * @param id
     */
    public void sendMsg2Friend(List<Object> params, Integer quote, Long id) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        PushMessage pushMessage = new PushMessage(config.getSessionKey(), id, params);
        pushMessage.setQuote(quote);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, new Gson().toJson(pushMessage));
        log.info("请求{}：", new Gson().toJson(pushMessage));
        MiraiApiUtil.httpPost(config.getRobotUrl() + "/sendFriendMessage", config.getSessionKey(),
                body, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        log.error(e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println(response.body().string());
                        response.close();
                    }
                });
    }

//    /**
//     * 发送XML消息（Api_SendXml）
//     * Api_SendXml	无返回值	发送XML消息
//     * --------------------------------------
//     * 响应QQ	文本型	机器人QQ
//     * 匿名	整数型	0为普通 1为匿名（匿名需要群开启）
//     * 信息类型	整数型	同Api_SendMsg 1好友 2群 3讨论组 4群临时会话 5讨论组临时会话
//     * 收信群_讨论组	文本型	发群内、临时会话必填 好友可不填
//     * 收信对象	文本型	临时会话、好友必填 发至群内可不填
//     * ObjectMsg	文本型	XML代码
//     * 结构子类型	整数型	00 基本 02 点歌 其他不明 ，默认为0即可
//     * ---------------------------
//     * @param params
//     * @return
//     */
//    public Map<String, Object> sendXml(Map<String, Object> params) {
//        init();
//        PushMessage pushMessage = new PushMessage("Api_SendXml", token, params);
//        return HttpApiUtil.sendPost(host, port, pushMessage);
//    }
//
//
//    /**
//     * 置群验证事件（Api_HandleGroupEvent）
//     * Api_HandleGroupEvent	无返回值	某人请求加入群聊验证处理
//     * 响应QQ	文本型	机器人QQ
//     * data	文本型	MQ_原始信息
//     * 处理方式	整数型	10同意 20拒绝 30或0忽略
//     * 附加信息	文本型	拒绝时的附加信息
//     * 拒绝不再接受	整数型	1为真，慎用
//     */
//    public Map<String, Object> handleGroupEvent(Map<String, Object> params) {
//        init();
//        PushMessage pushMessage = new PushMessage("Api_HandleGroupEvent", token, params);
//        return HttpApiUtil.sendPost(host, port, pushMessage);
//    }
//
//
//
//    public Map<String, Object> handleFriendEvent(Map<String, Object> params) {
//        init();
//        PushMessage pushMessage = new PushMessage("Api_HandleFriendEvent", token, params);
//        return HttpApiUtil.sendPost(host, port, pushMessage);
//    }
//
//    /**
//     * 上传图片（Api_UpLoadPic）
//     * Api_UpLoadPic	文本型	上传图片，成功返回该图片GUID（格式为[pic={E9A12BBC-A5F9-1074-40D7-D1F229B4CA05}.png]），失败返回空
//     * 响应QQ	文本型	机器人QQ
//     * 上传类型	整数型	1好友、临时会话 2群、讨论组 Ps：好友临时会话用类型 1，群讨论组用类型 2；当填写错误时，图片GUID发送不会成功
//     * 参考对象	文本型	上传该图片所属的群号或QQ
//     * 图片地址	文本型	本地路径或者网络图片地址
//     *
//     * @param params
//     * @return
//     */
//    public Map<String, Object> upLoadPic(Map<String, Object> params) {
//        init();
//        PushMessage pushMessage = new PushMessage("Api_UpLoadPic", token, params);
//        return HttpApiUtil.sendPost(host, port, pushMessage);
//    }
//
//

//
//    public Map<String, Object> withDrawMsg(Map<String, Object> params) {
//        init();
//        PushMessage pushMessage = new PushMessage("Api_WithdrawMsg", token, params);
//        return HttpApiUtil.sendPost(host, port, pushMessage);
//    }
//


}
